import 'dart:async';
import 'dart:collection';
import 'package:just_audio/just_audio.dart';
import '../models/generated_content.dart';
import 'content_generator.dart';
import 'tts_service.dart';

class AudioItem {
  final GeneratedContent content;
  final String audioUrl;
  final Duration duration;

  AudioItem({
    required this.content,
    required this.audioUrl,
    required this.duration,
  });
}

class AudioManager {
  static const int _bufferSize = 3;
  static const int _concurrentRequests = 5;
  final ContentGenerator _contentGenerator = ContentGenerator();
  final TTSService _ttsService = TTSService();
  final AudioPlayer _audioPlayer = AudioPlayer();
  
  final Queue<AudioItem> _audioBuffer = Queue<AudioItem>();
  StreamController<bool>? _bufferController;
  Timer? _checkTimer;
  bool _isGenerating = false;
  String? _productId;
  int _activeRequests = 0;

  Stream<bool> get bufferStream => _bufferController?.stream ?? const Stream.empty();
  int get bufferCount => _audioBuffer.length;
  bool get hasAudio => _audioBuffer.isNotEmpty;

  void init({String? productId}) {
    _productId = productId;
    if (_productId != null) {
      _contentGenerator.setProductId(_productId!);
    }
    _bufferController = StreamController<bool>.broadcast();
    _startBufferCheck();
    // 只有在设置了productId后才自动填充缓冲区
    if (_productId != null) {
      _fillBuffer();
    }
  }
  
  void setProductId(String productId) {
    _productId = productId;
    _contentGenerator.setProductId(productId);
    // 清空现有缓冲区
    clearBuffer();
    // 重新填充缓冲区
    if (!_isGenerating) {
      _fillBuffer();
    }
  }
  
  void clearBuffer() {
    _audioBuffer.clear();
    _bufferController?.add(true);
  }

  void dispose() {
    _checkTimer?.cancel();
    _bufferController?.close();
    _audioBuffer.clear();
    _audioPlayer.dispose();
    _ttsService.dispose();
  }

  void _startBufferCheck() {
    _checkTimer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (_audioBuffer.length < _bufferSize && !_isGenerating) {
        print('[AudioManager] 缓冲检查 - 当前缓冲: ${_audioBuffer.length}/$_bufferSize, 正在生成: $_isGenerating');
        _fillBuffer();
      }
    });
  }

  Future<void> _fillBuffer() async {
    if (_isGenerating || _productId == null) return;
    _isGenerating = true;
    print('[AudioManager] 开始填充缓冲区...');

    try {
      final int needed = _bufferSize - _audioBuffer.length;
      if (needed <= 0) {
        print('[AudioManager] 缓冲区已满，无需填充');
        return;
      }
      
      print('[AudioManager] 需要生成 $needed 条音频');
      
      // 并发生成多条音频
      final List<Future<AudioItem?>> futures = [];
      for (int i = 0; i < needed && i < _concurrentRequests; i++) {
        futures.add(_generateSingleAudio(i));
      }
      
      print('[AudioManager] 启动 ${futures.length} 个并发请求');
      final results = await Future.wait(futures);
      
      // 将成功生成的音频添加到缓冲区
      int addedCount = 0;
      for (final audioItem in results) {
        if (audioItem != null) {
          _audioBuffer.add(audioItem);
          addedCount++;
        }
      }
      
      print('[AudioManager] 成功添加 $addedCount 条音频到缓冲区');
      _bufferController?.add(true);
      
      // 如果还没满，继续填充
      if (_audioBuffer.length < _bufferSize) {
        print('[AudioManager] 缓冲区未满 (${_audioBuffer.length}/$_bufferSize)，继续填充...');
        await _fillBuffer();
      }
    } catch (e) {
      print('[AudioManager] 填充缓冲区失败: $e');
    } finally {
      _isGenerating = false;
      print('[AudioManager] 填充缓冲区结束，当前缓冲: ${_audioBuffer.length}/$_bufferSize');
    }
  }
  
  Future<AudioItem?> _generateSingleAudio(int index) async {
    try {
      _activeRequests++;
      print('[AudioManager] 请求[$index] 开始生成音频，活跃请求数: $_activeRequests');
      
      // 生成文本内容
      final startTime = DateTime.now();
      final content = await _contentGenerator.generateSingleContent();
      final textDuration = DateTime.now().difference(startTime).inMilliseconds;
      print('[AudioManager] 请求[$index] 文本生成完成，耗时: ${textDuration}ms，文本长度: ${content.text.length}');
      
      // 转换为语音
      final ttsStartTime = DateTime.now();
      final ttsResponse = await _ttsService.generateSpeech(content.text);
      final ttsDuration = DateTime.now().difference(ttsStartTime).inMilliseconds;
      print('[AudioManager] 请求[$index] TTS完成，耗时: ${ttsDuration}ms，成功: ${ttsResponse.isSuccess}');
      
      if (ttsResponse.isSuccess && ttsResponse.audioFiles.isNotEmpty) {
        // 获取音频URL
        final audioUrl = ttsResponse.audioFiles.first.url;
        print('[AudioManager] 请求[$index] 音频URL: $audioUrl');
        
        // 获取音频时长
        final duration = await _getAudioDuration(audioUrl);
        print('[AudioManager] 请求[$index] 音频时长: ${duration.inSeconds}秒');
        
        return AudioItem(
          content: content,
          audioUrl: audioUrl,
          duration: duration,
        );
      } else {
        print('[AudioManager] 请求[$index] TTS失败，响应无效');
        return null;
      }
    } catch (e) {
      print('[AudioManager] 请求[$index] 生成音频失败: $e');
      return null;
    } finally {
      _activeRequests--;
      print('[AudioManager] 请求[$index] 结束，剩余活跃请求数: $_activeRequests');
    }
  }

  Future<Duration> _getAudioDuration(String audioUrl) async {
    try {
      // 使用just_audio获取音频时长
      await _audioPlayer.setUrl(audioUrl);
      final duration = _audioPlayer.duration ?? const Duration(seconds: 5);
      return duration;
    } catch (e) {
      print('获取音频时长失败: $e');
      // 返回默认时长
      return const Duration(seconds: 5);
    }
  }

  AudioItem? getNextAudio() {
    if (_audioBuffer.isEmpty) {
      print('[AudioManager] 获取下一个音频失败：缓冲区为空');
      return null;
    }
    
    final audio = _audioBuffer.removeFirst();
    print('[AudioManager] 取出音频，剩余缓冲: ${_audioBuffer.length}/$_bufferSize');
    _bufferController?.add(true);
    
    // 异步填充缓冲区
    if (_audioBuffer.length < _bufferSize && !_isGenerating) {
      print('[AudioManager] 缓冲区不足，触发异步填充');
      Future.microtask(() => _fillBuffer());
    }
    
    return audio;
  }

  List<AudioItem> peekBuffer() {
    return _audioBuffer.toList();
  }

  Future<void> addContent(GeneratedContent content) async {
    try {
      // 转换为语音
      final ttsResponse = await _ttsService.generateSpeech(content.text);
      
      if (ttsResponse.isSuccess && ttsResponse.audioFiles.isNotEmpty) {
        // 获取音频URL
        final audioUrl = ttsResponse.audioFiles.first.url;
        
        // 获取音频时长
        final duration = await _getAudioDuration(audioUrl);
        
        final audioItem = AudioItem(
          content: content,
          audioUrl: audioUrl,
          duration: duration,
        );
        
        _audioBuffer.add(audioItem);
        _bufferController?.add(true);
        
        print('添加语音到缓冲区: ${_audioBuffer.length}/$_bufferSize, 时长: ${duration.inSeconds}秒');
        
        // 如果缓冲区未满，继续填充
        if (_audioBuffer.length < _bufferSize && !_isGenerating) {
          Future.microtask(() => _fillBuffer());
        }
      }
    } catch (e) {
      print('添加内容失败: $e');
    }
  }
}